package cn.magictodo.weblog.admin.schedule;

import cn.magictodo.weblog.common.domain.dos.IpDo;
import cn.magictodo.weblog.common.domain.mapper.IpMapper;
import com.github.jaemon.dinger.DingerSender;
import com.github.jaemon.dinger.core.entity.DingerRequest;
import com.github.jaemon.dinger.core.entity.enums.MessageSubType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import static cn.magictodo.weblog.common.enums.RedisPrefixEnum.REDIS_IP_ID;

/**
 * @author liu
 * @since 2024-03-25 23:44
 */
@Component
@Slf4j
public class InitVVIpScheduledTask {

    @Autowired
    private DingerSender dingerSender;

    @Autowired
    private IpMapper ipMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Scheduled(cron = "0 55 23 * * ?") // 每天晚间 23 点55分执行
    @Async("threadPoolTaskExecutor")
    public void execute() {
        log.info("InitVVIpScheduledTask execute");
        // 当日日期
        LocalDate currDate = LocalDate.now();
//        获取当日IP独立访问量
        Long l = ipMapper.selectIPNumberByDate(currDate);
        dingerSender.send(MessageSubType.MARKDOWN,
                DingerRequest.request("今日博客IP访问量为"+l,"博客独立IP数"));
//        初始化博客
        List<IpDo> ipDos = ipMapper.selectIPByDate(currDate);
        ipDos.forEach(ipDo -> {
            Long id = ipDo.getId();
            String key = REDIS_IP_ID.getPrefix() + id;
//            查询redis中对应的值
            Object valueFromRedis = redisTemplate.opsForValue().get(key);
            Long vV = 1L;

            // 判断并转换为Long类型
            if (valueFromRedis instanceof Integer) {
               vV = ((Integer) valueFromRedis).longValue();
            } else if (valueFromRedis instanceof Long) {
                vV = (Long) valueFromRedis;
            } else if (valueFromRedis instanceof String) {
                try {
                    vV = Long.parseLong((String) valueFromRedis);
                } catch (NumberFormatException e) {
                    // 处理转换失败的情况
                    System.out.println("The string value from Redis cannot be parsed as a Long.");
                }
            } else {
                // 处理未知类型的情况
                System.out.println("The value retrieved from Redis is of an unsupported type for conversion to Long.");
            }

// 当转换成功后，vV现在就是一个Long类型的变量
            ipDo.setVisitView(vV);
            ipDo.setUpdateTime(LocalDateTime.now());
//            将值同步到数据库
            ipMapper.updateById(ipDo);
//            清除redis
            redisTemplate.delete(key);
        });
        log.info("InitVVIpScheduledTask execute end");
    }
}
